#include "Cats/CatStates/CatState.h"
#include "Cats/CatStates/CatState_Base_Chase.h"
#include "Cats/BaseCat.h"
#include "Cats/CatSpriteLoader.h"
#include "Character/Character.h"
#include "Map/GameMap.h"

CatState_Base_Chase::CatState_Base_Chase(BaseCat* pCatRef):CatState(pCatRef)
{

}

CatState_Base_Chase::~CatState_Base_Chase()
{

}

void CatState_Base_Chase::runOnEnter()
{
	//play animation for running
	_pCatRef->stopAllActions();
	_pCatRef->runAction(CatSpriteLoader::getCatAnimation(_pCatRef->getCatType(), CAT_ANIM_WALK));
}

void CatState_Base_Chase::onResume()
{
	CatState::onResume();

	runOnEnter();
}

void CatState_Base_Chase::update(float timeDiff)
{
	//update movement
	_pCatRef->move(timeDiff);

	//check for exit states
	//check for exit to obstacle
	if (hasHitObstacle())
		_pCatRef->setNextCatState(CAT_OBSTACLE);
	//check for exit to skill
	else if (isSkillReady())
		_pCatRef->setNextCatState(CAT_SKILL);
	//check for exit to attack
	else if (isInAttackRange())
		_pCatRef->setNextCatState(CAT_ATTACK);
	//check for exit to flank
	else if (hasPassedCharacter())
		_pCatRef->setNextCatState(CAT_FLANK);

}

void CatState_Base_Chase::onExit()
{
	CatState::onExit();
}

bool CatState_Base_Chase::hasHitObstacle()
{
	return _pGameMapRef->checkCollisionWithObstacles(_pCatRef->getRect(), _pCatRef->getPosition());
}

bool CatState_Base_Chase::hasPassedCharacter()
{
	//if cat is already infront of the character
	return _pCatRef->getPositionX() < _pCharRef->getPositionX();
}

bool CatState_Base_Chase::isSkillReady()
{
	//if skill is ready
	if(_pCatRef->isSkillAvailable() && _pCatRef->isSkillReady())
	{
		//use skill only when cat has moved into screen
		if( _pCatRef->getPositionX() < (CCDirector::sharedDirector()->getWinSize().width - 250))
			return true;
	}

	return false;
}

bool CatState_Base_Chase::isInAttackRange()
{
	return _pCatRef->getPosition().getDistanceSq(_pCharRef->getPosition()) < _pCatRef->getAttackRange() * _pCatRef->getAttackRange();
}
